package com.youkeda.yikao.web.control;

import com.google.code.kaptcha.Constants;
import com.youkeda.yikao.web.dao.ZhangyankunSpringUserMapper;
import com.youkeda.yikao.web.dataobject.ZhangyankunSpringUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @author ：xiong
 * @date ：Created in 2019/9/8 13:49
 * @description：注册验证
 * @modified By：
 */
@Controller
//适当修改
public class SignupControl {
    @Autowired
    private ZhangyankunSpringUserMapper zhangyankunSpringUserMapper;

    //注册页面
    @RequestMapping(path = "/signup")
    public ModelAndView signup(@ModelAttribute("userForm") ZhangyankunSpringUser user , Model model) {
        ModelAndView view = new ModelAndView();
        view.addObject(BindingResult.class.getName()+".userForm",
                model.asMap().get("userFormError"));
        view.setViewName("signup1");
        return view;
    }

    @RequestMapping("/user/signup")
    public RedirectView signup(@Valid ZhangyankunSpringUser user, BindingResult result, RedirectAttributes attributes,
                               @RequestParam("verEmail") String verEmail,@SessionAttribute(value = "emailcode", required = false) String sessionEmailCode,
                               @RequestParam("verImg") String captcha, HttpSession session, @RequestParam("verEmail") String emailcode) {
        RedirectView view = new RedirectView();
//        if (xionghongjieSpringUserMapper.selectByPrimaryKey(user.getName()) == null) {
//            attributes.addFlashAttribute("userForm", user);
//            view.setUrl("/signup");
//            return view;
//        }
        if (result.hasErrors()|| StringUtils.isBlank(emailcode) ||
                StringUtils.isBlank(verEmail)) {
            attributes.addFlashAttribute("userForm", user);
            attributes.addFlashAttribute("userFormError",result);
            view.setUrl("/signup");
            return view;
        } else {
            if (emailcode.equals(sessionEmailCode) && captcha.equals(session.getAttribute(Constants.KAPTCHA_SESSION_KEY))) {
                session.removeAttribute("emailcode");
                zhangyankunSpringUserMapper.insert(user);
                view.setUrl("/test1");
                return view;
            }
            else {
                attributes.addFlashAttribute("userForm", user);
                view.setUrl("/signup");
                return view;
            }
        }
    }
}
